﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using Mengsk.ERP.App.ViewModels;
using System.Threading.Tasks;
using Mengsk.ERP.Orders;
using Mengsk.ERP.Orders.TDOrderInterfaces;
using System.IO;
using Mengsk.ERP.Delivery;
using Mengsk.ERP.Database;

namespace Mengsk.ERP.App.Refused
{
    /// <summary>
    /// RefusedUserControl.xaml 的交互逻辑
    /// </summary>
    public partial class RefusedUserControl : UserControl, IUIPlugin
    {
        private ObservableCollection<OrderRefuesdViewModel> orderViewModels = new ObservableCollection<OrderRefuesdViewModel>();
        private DateTime time;

        public RefusedUserControl()
        {
            InitializeComponent();
        }

        public string Title { get { return "拒收返回登记"; } }

        public Control UIControl { get { return this; } }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            this.dgvOrders.ItemsSource = this.orderViewModels;
            this.orderViewModels.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(orderViewModels_CollectionChanged);
            this.dpDate.SelectedDate = DateTime.Now;
        }

        void orderViewModels_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            this.tbCount.Text = string.Format("当前共 {0} 条快递记录，共 {1} 双鞋子", this.orderViewModels.Select(obj => obj.SourceOrder.ERPID).Distinct().Count(), this.orderViewModels.Count);
        }

        private void Process(OrderRefuesdViewModel[] viewModels)
        {
            Dictionary<Order, List<OrderRefuesdViewModel>> orders = new Dictionary<Order, List<OrderRefuesdViewModel>>();
            Dictionary<Shop, TDOrderInterfaceBase> tdInters = TDOrderInterfaceBase.AllOrderInterfaces.ToDictionary(obj => obj.Shop);
            foreach (var item in viewModels)
            {
                if (orders.ContainsKey(item.SourceOrder) == false)
                {
                    orders.Add(item.SourceOrder, new List<OrderRefuesdViewModel>());
                }
                orders[item.SourceOrder].Add(item);
            }

            try
            {
                foreach (var orderKeyValuePair in orders)
                {
                    try
                    {
                        string newComment = null;
                        foreach (var refusedOrderViewModel in orderKeyValuePair.Value)
                        {
                            this.Dispatcher.Invoke(new Action(() =>
                            {
                                refusedOrderViewModel.State = "处理中";
                                newComment = orderKeyValuePair.Value[0].SellerComment.Trim();
                            }));
                        }

                        //第一步删除以前的数据 
                        int ret = OrderManager.Instance.DeleteOrderRefuesedByDeliveryNumberAndCompany(orderKeyValuePair.Key.DeliveryCompany, orderKeyValuePair.Key.DeliveryNumber);

                        string comment = null;
                        if (newComment == orderKeyValuePair.Key.SellerComment.Trim())
                        {
                            comment = orderKeyValuePair.Key.SellerComment + "  " + this.time.ToString("MM.dd") + "返回收到，检查完好";
                            if (orderKeyValuePair.Value.Count > 1)
                            {
                                comment += "共" + orderKeyValuePair.Value.Count + "双";
                            }
                        }
                        else
                        {
                            comment = newComment;
                        }
                        if (orderKeyValuePair.Key.Flag == OrderFlag.UN_LABEL)
                        {
                            orderKeyValuePair.Key.Flag = OrderFlag.RED;
                        }
                        tdInters[orderKeyValuePair.Key.Shop].UpdateOrderComment(orderKeyValuePair.Key.POPID, orderKeyValuePair.Key.Flag, comment);

                        //插入拒收
                        OrderManager.Instance.InsertOrderRefuseds(orderKeyValuePair.Value.Select(obj => obj.Source).ToArray());
                        //插入收到物流记录
                        DeliveryManager.Instance.Insert(new Delivery.ArrvieInDelivery
                        {
                            DeliveryCompany = orderKeyValuePair.Key.DeliveryCompany,
                            DeliveryNumber = orderKeyValuePair.Key.DeliveryNumber,
                            ArriveReason = "拒收件返回",
                            CreateTime = DateTime.Now,
                            Comment = orderKeyValuePair.Key.Name
                        });
                        //更新订单状态
                        orderKeyValuePair.Key.SellerComment = comment;
                        int updated = DBHelper.Instance.Update("", OrderManager.TABLE_ORDER, "ERPID='" + orderKeyValuePair.Key.ERPID + "'", null, orderKeyValuePair.Key, true, "Flag", "State", "SellerComment");
                        foreach (var orderItem in orderKeyValuePair.Value)
                        {
                            this.Dispatcher.Invoke(new Action(() => orderItem.State = "处理成功"));
                            orderItem.Source.SellerComment = comment;
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnMakeReturn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.time = this.dpDate.SelectedDate.Value;
                Task.Factory.StartNew(new Action(() => this.Process(this.orderViewModels.ToArray())));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("是否要清空", "警告", MessageBoxButton.YesNo) != MessageBoxResult.Yes)
            {
                return;
            }
            this.orderViewModels.Clear();
        }

        private void LoadOrder(string deliveryNumber)
        {
            if (deliveryNumber.Contains("-"))
            {
                var items = deliveryNumber.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
                int index = 0, max = -1;
                for (int i = 0; i < items.Length; i++)
                {
                    if (max < items[i].Length)
                    {
                        max = items[i].Length;
                        index = i;
                    }
                }
                deliveryNumber = items[index];
            }

            Order[] orders = ERP.Orders.OrderManager.Instance.GetOrdersByDeliveryNumber(deliveryNumber);
            if (orders.Length < 1)
            {
                throw new Exception("未找到订单");
            }

            if (orders.Length > 1)
            {
                throw new Exception("请注意该物流编号找到多个订单无法处理");
            }
            Order order = null;

            if (this.cbGetLast.IsChecked.Value == true)
            {
                order = TDOrderInterfaceBase.GetOrderInterfaceSource(orders[0].Shop).DownLoadOrder(orders[0].POPID, orders[0].CreateTime, false);
                if (order == null)
                {
                    throw new Exception("无法从网络中下载订单");
                }
            }
            else
            {
                order = orders[0];
            }
            order.DeliveryCompany = orders[0].DeliveryCompany;
            order.DeliveryNumber = orders[0].DeliveryNumber;
            order.ERPID = orders[0].ERPID;

            List<OrderRefused> refusedItems = new List<OrderRefused>();
            foreach (var item in order.Items)
            {
                for (int i = 0; i < item.Count; i++)
                {
                    OrderRefused tmpItem = new OrderRefused
                    {
                        ERPID = order.ERPID,
                        PopID = order.POPID,
                        Shop = order.Shop,
                        Name = order.Name,
                        InternalName = item.InternalName,
                        SellerComment = order.SellerComment,
                        ReturnTime = DateTime.Now,
                        Color = item.Color,
                        Size = item.Size,
                        DeliveryCompany = orders[0].DeliveryCompany,
                        DeliveryNumber = deliveryNumber,
                    };
                    refusedItems.Add(tmpItem);
                }
            }
            var viewModels = refusedItems.Select(obj => new OrderRefuesdViewModel(obj) { SourceOrder = order }).ToArray();
            foreach (var viewModel in viewModels)
            {
                this.orderViewModels.Add(viewModel);
            }
            this.tbDeliveryNumber.Text = "";
        }

        private void tbDeliveryNumber_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Enter)
            {
                return;
            }
            e.Handled = true;

            try
            {
                string delivertyNumber = this.tbDeliveryNumber.Text.Trim();
                if (string.IsNullOrWhiteSpace(delivertyNumber))
                {
                    return;
                }
                if (this.cbAppendD.IsChecked.Value)
                {
                    delivertyNumber = "D" + delivertyNumber;
                }

                this.LoadOrder(delivertyNumber);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void DeleteOrder_Click(object sender, RoutedEventArgs e)
        {
            OrderRefuesdViewModel order = (e.Source as Hyperlink).DataContext as OrderRefuesdViewModel;
            if (order == null)
            {
                return;
            }

            this.orderViewModels.Remove(order);
        }

        private void tbDeliveryNumber_GotFocus(object sender, RoutedEventArgs e)
        {
            this.Dispatcher.BeginInvoke(new Action(() => (sender as TextBox).SelectAll()));
        }

        private void btnImport_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
                ofd.Filter = "TXT|*.txt|All|*.*";
                if (ofd.ShowDialog().Value == false)
                {
                    return;
                }
                Task.Factory.StartNew(new Action(() => this.ProcessTask(ofd.FileName)));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ProcessTask(string file)
        {
            StreamReader st = null;
            try
            {
                st = new StreamReader(file, Encoding.Default);

                string deliveryNumber = st.ReadLine();

                while (string.IsNullOrWhiteSpace(deliveryNumber) == false)
                {
                    this.Dispatcher.Invoke(new Action(() =>
                        {
                            this.tbDeliveryNumber.Text = deliveryNumber;
                            try
                            {
                                this.LoadOrder(deliveryNumber);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                        }));
                    deliveryNumber = st.ReadLine();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (st != null)
                {
                    st.Close();
                }
            }
        }
    }
}
